<template>
  <div class="login">
    <div class="login-box">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="medium"
      >
        <!-- <h3 class="title">网域网站内容管理系统</h3> -->
        <!-- <h2 class="title" :style="captchaOnOff?'margin-top:40px':''">网域网站内容管理系统</h2> -->
        <!-- <h2 class="title" :style="captchaOnOff?'margin-top:40px':''">2022年国家级教学成果奖<br>信息发布平台</h2> -->

        <h2 class="title" :style="captchaOnOff ? 'margin-top:40px' : ''">
          {{ loginTitle }}
        </h2>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            show-password
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox
          v-model="loginForm.rememberMe"
          style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        >
        <p
          style="color: red; float: right; padding: 0; margin: 0"
          v-if="smsFlag"
        >
          连续登录失败超出5次,账号将被锁定。
        </p>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width: 100%"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="liulanqi">
      <p>
        兼容常见的 PC 浏览器：Chrome，Firefox，Edge，QQ 浏览器-极速模式，360
        浏览器-极速模式
      </p>
    </div>
    <!--  底部  -->
    <div class="el-login-footer" v-if="false">
      <span>Copyright © 2018-2021 ruoyi.vip All Rights Reserved.</span>
    </div>

    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="400px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      style="margin-top: 30vh"
    >
      <el-form :model="ticketForm" label-width="60px" :rules="rules">
        <el-form-item label="问题" prop="dictLabel">
          <el-select
            v-model="ticketForm.dictLabel"
            placeholder="请选择问题"
            style="width: 100%"
          >
            <el-option
              v-for="item in questionList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input
            v-model="ticketForm.answer"
            autocomplete="off"
            placeholder="请输入答案"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reset">取 消</el-button>
        <el-button type="primary" @click="ticketFormSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      ref="dialog"
      width="40%"
      title="初始密码修改"
      :show-close="false"
      :visible="dialogFirstLoginVisible"
      custom-class="center-dialog"
    >
      <el-steps :active="active">
        <el-step title="初次登录" />
        <el-step title="修改初始密码" />
        <el-step title="完成" />
      </el-steps>
      <div v-if="active == 1" class="topTip">
        您好，为了您的账号安全，请点击下一步修改初始密码
      </div>
      <div
        v-if="active != 3"
        style="width: 80%; margin: 10px auto 20px; text-align: center"
      >
        <el-form
          ref="firstLoginFormRef"
          :model="firstLoginForm"
          :rules="firstLoginRules"
          label-width="120px"
        >
          <el-row v-show="active == 1">
            <el-col :span="24">
              <el-form-item label="用户名：">
                <el-input
                  v-model="loginId"
                  :disabled="false"
                  readonly
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="active == 2">
            <el-col :span="24">
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input
                  v-model="firstLoginForm.oldPassword"
                  placeholder="请输入旧密码"
                  maxlength="50"
                  type="password"
                  show-password
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="新密码" prop="newPassword">
                <el-popover
                  ref="popover"
                  placement="right"
                  width="300"
                  trigger="focus"
                >
                  <span>
                    必须使用字母、数字和特殊字符组成强口令，<br />长度不小于6个字符，不超过15个字符，注意不要使用空格。
                  </span>
                  <el-input
                    slot="reference"
                    v-model="firstLoginForm.newPassword"
                    placeholder="请输入密码"
                    maxlength="50"
                    type="password"
                    show-password
                  />
                </el-popover>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="firstLoginForm.confirmPassword"
                  placeholder="请输入密码"
                  maxlength="50"
                  type="password"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div v-if="active != 1" slot="footer" class="dialog-footer">
          <el-button @click="resetForm('form')">上一步</el-button>
          <el-button
            type="primary"
            @click="submitFirstLoginForm('firstLoginFormRef')"
            >下一步</el-button
          >
        </div>
        <div v-else slot="footer" class="dialog-footer">
          <el-button type="primary" @click="nextTip">下一步</el-button>
        </div>
      </div>
      <div v-if="active === 3" class="ImgTip">
        <div style="margin: 20px 0">
          <svg-icon
            v-if="isSuccess === true"
            icon-class="pwdSuccess"
            style="font-size: 40px"
          />
          <svg-icon v-else icon-class="pwdFail" style="font-size: 40px" />
        </div>
        <p v-if="isSuccess === true">修改密码成功</p>
        <p v-else>系统开小差了，导致密码修改失败，请重新修改</p>
        <el-button
          v-if="isSuccess === true"
          type="primary"
          @click="returnDialogTableVisible"
          >重新登录</el-button
        >
        <el-button v-else type="primary" @click="again">重新修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCodeImg,
  getSecurityQuestionList, // 05、读取安全问题列表
  verificationSecurityQuestionList, // 验证安全问题
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { getToken } from "@/utils/auth";

export default {
  name: "Login",
  inject: ["tour"],
  data() {
    const validatePassword = (rule, value, callback) => {
      let mode = 0;
      if (!value) {
        callback(new Error("密码不能为空"));
      } else if (value.length < 6 || value.length > 15) {
        callback(new Error("长度为6-15个字符"));
      } else {
        if (/\d/.test(value)) mode++; //数字
        if (/[A-Z]/.test(value)) mode++; //大写字母
        if (/[a-z]/.test(value)) mode++; //小写字母
        if (/[\W_]/.test(value)) mode++; //特殊字符

        if (mode < 3) {
          callback(new Error("必须包含大写字母、小写字母、数字、符号3种"));
        }
        callback();
      }
    };
    const validatecheckPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("确认密码不能为空"));
      } else if (value != this.pwdOverTimeForm.newPassword) {
        callback(new Error("两次输入的密码必须一致!"));
      } else {
        callback();
      }
    };
    const validatecheckPassword2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("确认密码不能为空"));
      } else if (value != this.firstLoginForm.newPassword) {
        callback(new Error("两次输入的密码必须一致!"));
      } else {
        callback();
      }
    };
    return {
      dialogFirstLoginVisible: false,
      smsFlag: false,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: process.env.NODE_ENV === "development" ? "dsnwwz" : "",
        password: process.env.NODE_ENV === "development" ? "Gyx,05896." : "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      ticketForm: {
        ticket: "",
      },
      loginTitle: `${process.env.VUE_APP_TITLE} ${process.env.VUE_APP_BANBEN}`,
      open: false,
      title: "",
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        code: [
          { required: true, trigger: "change", message: "验证码不能为空" },
        ],
      },
      rules: {
        dictLabel: [
          { required: true, trigger: "blur", message: "问题不能为空" },
        ],
        answer: [{ required: true, trigger: "blur", message: "答案不能为空" }],
      },
      // 表单校验
      firstLoginRules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [
          { required: true, validator: validatePassword, trigger: "blur" },
        ],
        confirmPassword: [
          {
            required: true,
            validator: validatecheckPassword2,
            trigger: "blur",
          },
        ],
      },
      loading: false,
      captchaOnOff: false,
      redirect: undefined,
      questionList: [],
    };
  },
  computed: {
    loginId() {
      return this.$store.state.user.loginId;
    },
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
    this.getList();
  },
  methods: {
    getList() {
      getSecurityQuestionList().then((res) => {
        this.questionList = res.data;
      });
    },
    getCode() {
      getCodeImg().then((res) => {
        this.captchaOnOff =
          res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.smsFlag = false;
          this.loading = true;
          console.log("getToken(): ", getToken());
          if (getToken()) {
            alert("11");
            this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            return;
          }
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }

          this.$store
            .dispatch("Login", this.loginForm)
            .then((res) => {
              if (res.code == 203) {
                this.open = true;
                this.title = "双因子验证";
                this.ticketForm.ticket = res.ticket;
                return;

                this.$prompt("请输入邮箱", "双因子验证", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                })
                  .then(({ value }) => {
                    this.$message({
                      type: "success",
                      message: "你的邮箱是: " + value,
                    });
                  })
                  .catch(() => {
                    this.$message({
                      type: "info",
                      message: "取消输入",
                    });
                  });
                return;
              }

              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            // .then(()=>{
            //   this.$nextTick(()=>{
            //     setTimeout(() => {
            //   this.tour.$refs.tour.init()
            //     }, 1000);
            //   })
            // })
            .catch(() => {
              this.smsFlag = true;
              this.loading = false;
              if (this.captchaOnOff) {
                this.getCode();
              }
            });
        }
      });
    },
    submitFirstLoginForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updateUserPwd(
            this.firstLoginForm.oldPassword,
            this.firstLoginForm.newPassword
          )
            .then((res) => {
              this.nextTip();
              if (res.code == 200) {
                this.isSuccess = true;
              } else {
                this.isSuccess = false;
              }
            })
            .then(() => {});
        }
      });
    },
    /**
     * 双因子认证登录
     */
    ticketFormSubmit() {
      // this.ticketForm.ticket = this.ticket;
      this.$store
        .dispatch("TwoLogin", this.ticketForm)
        .then((res) => {
          this.$router.push({ path: this.redirect || "/" }).catch(() => {});
        })
        .catch(() => {
          this.smsFlag = true;
          this.loading = false;
          if (this.captchaOnOff) {
            this.getCode();
          }
        });
      // verificationSecurityQuestionList(this.ticketForm).then((res) => {
      // });
    },
    reset() {
      this.ticketForm = {};
      this.$message({
        type: "info",
        message: "取消登录",
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/bg.png");
  background-size: cover;
}
.title {
  margin: 60px auto 44px;
  font-weight: bold;
  color: #2c3645;
  text-align: center;
  font-size: 22px;
}
.login-box {
  width: 855px;
  // height: 508px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: url("../assets/images/login-bg.png") no-repeat 0 50% #f5f7ff;
  background-size: 50%;
  border-radius: 12px;
}
.login-form {
  float: right;
  height: 100%;
  padding: 40px;
  border-radius: 6px;
  background: #ffffff;
  width: 446px;
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.liulanqi {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  color: #fff;
  width: 100%;
  text-align: center;
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
::v-deep .el-form-item {
  margin-bottom: 30px;
  .el-form-item__content {
    line-height: 42px;
    .el-input {
      height: 42px;
      .el-input__inner {
        height: 42px;
        line-height: 42px;
      }
    }
    .input-icon {
      height: 42px;
      width: 14px;
      margin-left: 2px;
    }
  }
}
</style>
<style scoped>
/* @media screen and (max-width: 1200px) {.login-box{
    height: 50%;

  }
  .title {
    margin: 40px auto 10px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 10px;
  }
} */
@media screen and (max-height: 800px) {
  .login-box {
    /* max-height: 50%; */
  }
  .login-form {
    padding: 10px;
  }
  .title {
    margin: 40px auto 10px;
  }
  .liulanqi {
    bottom: 20px;
  }
  ::v-deep .el-form-item {
    margin-bottom: 15px;
  }
}
@media screen and (max-width: 992px) {
  .login-box {
    width: auto;
  }
  .login-form {
    float: unset;
    padding: 20px;
  }
}
</style>
